
let _ctx;
let _datas;
let _msg;
let _avatars;

const isEmptyNum = (num)=>{
	return num === undefined || num === null;
};

// 绘制一个
const drawRankItem = (data, info)=>{
	const x = info.x || 0;

	// 名次
    _ctx.fillStyle = data.openid === info.openid ? "#a6ff2e" : "#ffffff";	
    _ctx.textAlign = "center";
    _ctx.baseLine = "middle";
    _ctx.font = `${info.indexFontSize}px Helvetica`;
    _ctx.fillText(data.index, info.indexPos.x + x, info.indexPos.y);

    // 头像
    try {
    	if (_avatars[data.openid]) {
	    	_ctx.drawImage(_avatars[data.openid], info.avatarRect.x + x, info.avatarRect.y, info.avatarRect.w, info.avatarRect.h);
	    } else {
	    	const img = gg.createImage();
	    	img.src = data.avatarUrl;
	    	img.onload = ()=> {
	    		_avatars[data.openid] = img;
	    		_ctx.drawImage(_avatars[data.openid], info.avatarRect.x + x, info.avatarRect.y, info.avatarRect.w, info.avatarRect.h);
	    	}
	    }
    } catch (ex) {
    	console.log(ex, data);
    }

    // 昵称
    _ctx.fillStyle = "#ffffff";
    _ctx.textAlign = "center";
    _ctx.baseLine = "middle";
    _ctx.font = `${info.nicknameFontSize}px Helvetica`;
    _ctx.fillText(data.nickname, info.nicknamePos.x + x, info.nicknamePos.y);

    // 分数
    _ctx.fillStyle = "#ffffff";
    _ctx.textAlign = "center";
    _ctx.baseLine = "middle";
    _ctx.font = `${info.scoreFontSize}px Helvetica`;
    _ctx.fillText(data.score, info.scorePos.x + x, info.scorePos.y);
};

const onDrawRank = ()=>{
	_ctx.clearRect(0, 0, _msg.canvasWidth, _msg.canvasHeight);

	if (isEmptyNum(_msg.itemWidth)) {
		_msg.itemWidth = 180;
	}
	if (isEmptyNum(_msg.indexFontSize)) {
		_msg.indexFontSize = 70;
	}
	if (!_msg.indexPos) {
		_msg.indexPos = {x: 90, y: 70};
	}
	if (isEmptyNum(_msg.nicknameFontSize)) {
		_msg.nicknameFontSize = 30;
	}
	if (!_msg.nicknamePos) {
		_msg.nicknamePos = {x: 90, y: 250};
	}
	if (!_msg.avatarRect) {
		_msg.avatarRect = {x: 40, y: 90, w: 100, h: 100};
	}
	if (isEmptyNum(_msg.scoreFontSize)) {
		_msg.scoreFontSize = 40;
	}
	if (!_msg.scorePos) {
		_msg.scorePos = {x: 90, y: 310};
	}
	
	const info = {};
	for (const key in _msg) {
		info[key] = _msg[key];
	}

	for (let i = 0; i < _datas.length; ++i) {
		info.x = i * _msg.itemWidth;
		drawRankItem(_datas[i], info);
	}
};



const init = (ctx, datas, msg, avatars)=>{
	_ctx = ctx;
	_datas = datas;
	_msg = msg;
	_avatars = avatars;

	msg.isDebug && console.log(datas);

	onDrawRank();
};



module.exports = {
	init,
	onDrawRank
};